#include "ResText.h"
#include "D3D9Engine.h"


CResourceText::CResourceText()
{
	_text = NULL;
	_dxFont = NULL;
	_fontName = NULL;
	_size = 12;
	_bold = _italic = _underline = false;

	//node settings
	_type = NODE_ENTITY_ELEMENT;
	_entity = ENTITY_TEXT;

	this->SetColliding(false);
}


CResourceText::~CResourceText()
{
	SAFE_DELETE_ARRAY(_text);
}


bool CResourceText::OnInitResource(ICompHandler *handler)
{
	HRESULT hr;

	CD3D9Engine* ptrEngine = (CD3D9Engine*)handler;

	if(ptrEngine)
	{
		UINT weight = (_bold) ? FW_BOLD : FW_NORMAL;
		int lHeight;

		lHeight = -MulDiv(_size, GetDeviceCaps(GetDC(NULL), LOGPIXELSY), 72);


		hr = D3DXCreateFont(ptrEngine->GetDevice(), 
							lHeight, 
							0, 
							weight, 
							0,
							_italic,
							ANSI_CHARSET,
							OUT_DEFAULT_PRECIS,
							ANTIALIASED_QUALITY,
							DEFAULT_PITCH | FF_DONTCARE,
							_fontName,
							&_dxFont);

		if(FAILED(hr))
			return false;

	}

	return true;
}


bool CResourceText::OnFreeResource(ICompHandler *handler)
{
	SAFE_RELEASE(_dxFont);

	return true;
}


bool CResourceText::CreateFontA(const char *font, int size, bool bold, bool italic, bool underline)
{
	_fontName = (char*)font;
	_size = size;
	_bold = bold;
	_italic = italic;
	_underline = underline;

	return true;
}


void CResourceText::Render(LPDIRECT3DDEVICE9 rendererDevice, D3DXMATRIX* transform)
{
	if(rendererDevice &&
		_dxFont)
	{
		RECT rect;
		D3DXMATRIX transformation = (transform == NULL)? this->WorldTransformation : (*transform);

		SetRect(&rect, (int)transformation(3, 0), (int)transformation(3, 1), 100, 100);

		if(0 != _dxFont->DrawText(NULL, _text, -1, &rect, DT_CALCRECT, NULL))
		{
			_dxFont->DrawText(NULL, _text, -1, &rect, DT_NOCLIP, this->Color);
		}
	}
}


char* CResourceText::Text(char* text)
{
	if(text == NULL)
		return _text;
	else
	{
		SAFE_DELETE_ARRAY(_text);

		int size = (int)strlen(text);
		_text = new char[size + 1];

		memcpy(_text, text, size);

		_text[size] = '\0';
		return _text;
	}
}